# http://seb.box.re/articles/2006/07/29/foreign-key-and-rails-migration

module MigrationHelper

  # Non-rails-standard helper to
  # facilitate managing foreign key constraints.

  module ForeignKeys
    
    def add_foreign_key(from_table, from_column, to_table)
      sql_statement = %W{  alter table #{from_table}
                               add constraint #{self.to_fk_constraint_name( from_table, from_column)}
                               foreign key (#{from_column})
                               references #{to_table}(id)  }
      sql_statement = sql_statement.join(' ')
      execute sql_statement
    end

    def drop_foreign_key(from_table, from_column, to_table)
      execute "alter table #{from_table} DROP CONSTRAINT #{self.to_fk_constraint_name(from_table, from_column)}"
    end

    def to_fk_constraint_name(from_table, from_column)
      return "fk_#{from_table}_#{from_column}"
    end

  end

 end